package com.xms.consumers.ribbonbutton;

import com.xms.ribbonbutton.entity.RibbonButton;
import com.xms.ribbonbutton.event.CreateDefaultButtonsEvent;
import com.xms.ribbonbutton.service.IDefaultButtonProvider;
import com.xms.ribbonbutton.service.IRibbonButtonCreaterService;
import com.xms.schema.core.EntityMask;
import com.xms.utils.CollectionUtil;
import com.xms.utils.UUIDUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 实体创建事件消费者之创建默认按钮
 * </p>
 *
 * @author migo
 * @since 2021/9/29
 */
@Service
public class CreateDefaultRibbonButtonsConsumer {
    private IRibbonButtonCreaterService _ribbonButtonCreaterService;
    private IDefaultButtonProvider _defaultButtonProvider;

    @Autowired
    public CreateDefaultRibbonButtonsConsumer(IRibbonButtonCreaterService ribbonButtonCreaterService, com.xms.ribbonbutton.service.IDefaultButtonProvider defaultButtonProvider) {
        _ribbonButtonCreaterService = ribbonButtonCreaterService;
        _defaultButtonProvider = defaultButtonProvider;
    }

    @SneakyThrows
    @Async
    @EventListener
    public void handleEvent(CreateDefaultButtonsEvent eventMessage) {
        if (CollectionUtil.notEmpty(eventMessage.DefaultButtons)) {
            List<RibbonButton> defaultButtons = _defaultButtonProvider.get(EntityMask.User.value());
            List<RibbonButton> buttons = defaultButtons.stream()
                    .filter(x -> eventMessage.DefaultButtons.stream()
                            .anyMatch(d -> d.equals(x.getRibbonbuttonid()))).collect(Collectors.toList());
            if (CollectionUtil.notEmpty(buttons)) {
                buttons.forEach(b ->
                {
                    b.setRibbonbuttonid(UUIDUtil.get());
                    b.setEntityid(eventMessage.source.getEntityid());
                    b.setStatecode(true);
                    b.setAuthorizationenabled(false);
                    b.setShowlabel(true);
                    b.setCreatedon(LocalDateTime.now());
                    b.setCreatedby(eventMessage.source.getCreatedby());
                });
                _ribbonButtonCreaterService.createMany(buttons);
            }
        }
    }
}
